package com.qianxun.watchdog;

import com.qianxun.framework.util.FileUtil;
import com.qianxun.framework.util.ObjectUtil;
import com.qianxun.watchdog.jar.JarGenerator;

import java.net.Socket;
import java.util.Arrays;


/**
 * @author: huwei
 * @date: 2020/10/15 13:15
 * @version: 1.0.0
 */
public class WatchdogBootstrapper {

    /**
     * 启动看门狗并监听当前应用
     * @throws Exception
     */
    public static void startup() throws Exception {
        try {
            Class<?> cls = Class.forName((new Throwable()).getStackTrace()[1].getClassName());
            Arrays.stream((new Throwable()).getStackTrace()).forEach(stackTraceElement -> System.out.println(stackTraceElement.getClassName()));
            startup(cls);
        }catch (Exception e){
            startup(WatchdogBootstrapper.class);
        }
    }

    public static void startup(Class<?> cls) throws Exception {
        String classPath = FileUtil.classPath(cls);
        if (classPath.indexOf(".jar") != -1) {
            String jarAbsPath = classPath.substring(0 ,classPath.indexOf(".jar") + ".jar".length());
            jarAbsPath = jarAbsPath.startsWith("file:") ? jarAbsPath.substring("file:".length()) : jarAbsPath;
            jarAbsPath = jarAbsPath.startsWith("jar:file:") ? jarAbsPath.substring("jar:file:".length()) : jarAbsPath;
            String jarName = jarAbsPath.lastIndexOf("/") != -1 ? jarAbsPath.substring(jarAbsPath.lastIndexOf("/") + 1) : jarAbsPath;
            startup(jarAbsPath, jarName);
        } else{
            throw new Exception("启动看门狗，监听应用失败，原因：被监听对象只能为jar应用；path:" + classPath );
     }
    }

    /**
     * 启动看门狗并监听指定java应用
     * @param jarAbsPath 监听java应用jar的决定路径
     * @param jarName 监听java应用的jar名称
     * @throws Exception
     */
    public static void startup(String jarAbsPath ,String jarName) throws Exception {
        if(ObjectUtil.isBlank(jarName) || ObjectUtil.isBlank(jarAbsPath) || jarName.indexOf(".jar") == -1){
            throw new Exception("启动看门狗，监听应用失败，原因：被监听对象只能为jar应用；jarAbsPath:" + jarAbsPath + " ; jarName:" + jarName);
        }

        String innerJarName = jarName.trim();
        String innerJarAbsPath = jarAbsPath.trim().endsWith(innerJarName) ? jarAbsPath.trim() : jarAbsPath.trim() + "/" + innerJarName;

        JarGenerator jarGenerator = new JarGenerator();
        if(!jarGenerator.isStartup()){
            jarGenerator.startup();
        }

        int count = 0 ;
        while(!jarGenerator.isStartup() && count <= 5){
            Thread.sleep(2000);
            count++;
        }

        //休眠5秒等待看门狗准备成功
        Thread.sleep(2000);

        if(jarGenerator.isStartup()){
            try {
                Socket socket = new Socket("127.0.0.1", 20259);
                FileUtil.write(socket.getOutputStream(), (innerJarName + innerJarAbsPath).getBytes());
            }catch (Exception e){
                throw new Exception("看门狗启动失败；");
            }
        }else{
            throw new Exception("看门狗启动失败；");
        }
    }

}
